package com.dctp.ems.controller;

import com.dctp.common.cache.ContractCache;
import com.dctp.common.cache.UserCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.CollectUtil;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Path("/sybStat")
public class SybStatController extends BaseController {

    public void sybAmountByType() {
        Long userId = getParaToLong("user_id");
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (StringUtil.isNotEmpty(startTime)) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }

        String sql = "SELECT type, SUM(amount) AS total_amount " +
                "FROM dctp_syb_fund_flow " +
                where +
                " GROUP BY type ORDER BY type";

        List<Record> results = Db.find(sql, params.toArray());

        // 组装成Map<Integer, BigDecimal>
        Map<Integer, BigDecimal> typeAmountMap = new HashMap<>();
        for (Record r : results) {
            Integer type = r.getInt("type");
            BigDecimal total = r.getBigDecimal("total_amount");
            typeAmountMap.put(type, total);
        }
        renderJson(JsonResult.successWithData(typeAmountMap));
    }


    public void sybFundFlowPage() {

        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);

        Long userId = getParaToLong("user_id", null);
        Integer type = getParaToInt("type", null);
        Integer fundType = getParaToInt("fund_type", null);
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (type != null) {
            where.append(" AND type = ?");
            params.add(type);
        }
        if (fundType != null) {
            where.append(" AND fund_type = ?");
            params.add(fundType);
        }
        if (StringUtil.isNotEmpty(startTime)) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }

        String select = "SELECT * ";
        String from = "FROM dctp_syb_fund_flow " + where + " ORDER BY create_time DESC";

        var p = Db.paginate(page, pageSize, select, from, params.toArray());

        if (CollectUtil.isNotEmpty(p.getList())) {
            for (Record r : p.getList()) {
                Long uid = r.getLong("user_id");
                Record user = UserCache.getBasic(uid);
                if (null != user) {
                    r.set("user",UserCache.getShowInfo(uid));
                    String key = getGroupByIdKey();
                    Long orgId = user.getLong(key);
                    if (null != orgId) {
                        Record showInfo = UserCache.getShowInfo(orgId);
                        r.set("orgInfo", showInfo);
                    }
                }
            }
        }

        renderJson(JsonResult.successWithData(
                new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }


    public void sybIncomePage() {

        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);

        Long userId = getParaToLong("user_id", null);
        Integer type = getParaToInt("type", null);
        Integer fundType = getParaToInt("fund_type", null);
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (type != null) {
            where.append(" AND type = ?");
            params.add(type);
        }
        if (fundType != null) {
            where.append(" AND fund_type = ?");
            params.add(fundType);
        }
        if (StringUtil.isNotEmpty(startTime)) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }

        String select = "SELECT * ";
        String from = "FROM dctp_syb_income_record " + where + " ORDER BY create_time DESC";

        var p = Db.paginate(page, pageSize, select, from, params.toArray());
        if (CollectUtil.isNotEmpty(p.getList())) {
            for (Record r : p.getList()) {
                Long uid = r.getLong("user_id");
                Record user = UserCache.getBasic(uid);
                r.set("create_time",r.getLocalDateTime("create_time").toLocalDate());
                if (null != user) {
                    r.set("user",UserCache.getShowInfo(uid));
                    String key = getGroupByIdKey();
                    Long orgId = user.getLong(key);
                    if (null != orgId) {
                        Record showInfo = UserCache.getShowInfo(orgId);
                        r.set("orgInfo", showInfo);
                    }
                }
            }
        }

        renderJson(JsonResult.successWithData(
                new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }



    public void sybAmountByTypePage() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);

        Long userId = getParaToLong("user_id", null);
        Integer type = getParaToInt("type", null);
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (type != null) {
            where.append(" AND type = ?");
            params.add(type);
        }
        if (StringUtil.isNotEmpty(startTime)) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (StringUtil.isNotEmpty(endTime)) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }

        String select = "SELECT f.user_id, " +
                "SUM(f.amount) AS total_amount, " +
                "SUM(CASE WHEN f.fund_type = 1 THEN f.amount ELSE 0 END) AS total_in, " +
                "SUM(CASE WHEN f.fund_type = 2 THEN f.amount ELSE 0 END) AS total_out, " +
                "SUM(CASE WHEN f.fund_type = 3 THEN f.amount ELSE 0 END) AS total_interest, " +
                "(SELECT IFNULL(SUM(ir.amount),0) FROM dctp_syb_income_record ir WHERE ir.user_id = f.user_id) AS total_income, " +
                "((SELECT IFNULL(SUM(ff.amount),0) FROM dctp_syb_fund_flow ff WHERE ff.user_id = f.user_id AND ff.fund_type != 3) " +
                " + (SELECT IFNULL(SUM(ir.amount),0) FROM dctp_syb_income_record ir WHERE ir.user_id = f.user_id)) AS total_balance ";

        String from = "FROM dctp_syb_fund_flow f " +
                where +
                " GROUP BY f.user_id ORDER BY total_balance DESC";

        var pageData = Db.paginate(page, pageSize, select, from, params.toArray());
        if (CollectUtil.isNotEmpty(pageData.getList())) {
            for (Record r : pageData.getList()) {
                Long uid = r.getLong("user_id");
                Record user = UserCache.getBasic(uid);
                if (null != user) {
                    r.set("user",UserCache.getShowInfo(uid));
                    String key = getGroupByIdKey();
                    Long orgId = user.getLong(key);
                    if (null != orgId) {
                        Record showInfo = UserCache.getShowInfo(orgId);
                        r.set("orgInfo", showInfo);
                    }
                }
            }
        }

        renderJson(JsonResult.successWithData(
                new PageResult<>(pageData.getList(), pageData.getTotalRow(), pageSize, page)
        ));
    }
}
